using System;
using Core;
using UnityEngine;

namespace g_gongjianta
{
    [Event(GameEvent.ENTER)]
    public class GameEnterHandler : Core.Component, IEventHandler
    {
        public void Run()
        {
            log.d($"GameEnter {G.Name}");

            if (G is Core.GameContext gameContext)
            {
                var orientation = gameContext.Conf.Orientation;
                G.UI.SetSceneOrientation(orientation);
                S.UI.SetSceneOrientation(orientation);
            }

            LoadCameraDriver();
            
            //禁用Unity自带的物理系统
            Physics2D.gravity = Vector2.zero;
            Physics2D.simulationMode = SimulationMode2D.Script;

            // S.UI.Show((int)ESysWnd.tips_wnd);
            G.Scene.Switch((int)EScene.Login);
        }

        private void LoadCameraDriver()
        {
            log.err("LoadCameraDriver");
            var root = G.mono;
            var cameraDriver = root.transform.Find("CameraDriver")?.gameObject;
            if (cameraDriver != null)
            {
                return;
            }

            var asset = G.Res.LoadSync("Res/Prefabs/Scene/CameraDriver.prefab");
            if (asset == null)
            {
                throw new Exception("Failed to load CameraDriver");
            }

            cameraDriver = GameObject.Instantiate(asset.Obj, root.transform, true) as GameObject;

            if (cameraDriver == null)
            {
                throw new Exception("Failed to Instantiate CameraDriver");
            }

            cameraDriver.name = "CameraDriver";
            var mainCamera = cameraDriver.GetComponentInChildren<Camera>();
            Utils.Camera.InitMainCamera(mainCamera, G.UI.Camera);
        }
    }
}